<!-- 文本框 -->
<template>
  <van-field
    v-show="!props.hidden"
    :name="props.formItem?.id"
    :label="props.formItem?.title"
    :placeholder="props.placeholder"
    :rules="rules"
    :required="props.required"
    :readonly="props.readonly"
    :input-align="FieldInputAlign.DEFAULT"
    clearable
  >
    <template #input>
      <van-uploader
        v-model="_value"
        :multiple="maxNumber > 1"
        :max-count="maxNumber > 0 ? maxNumber : 99"
        :max-size="maxSize * 1024 * 1024"
        upload-text="选择图片"
        :after-read="afterRead"
      />
      <!-- <uploader
        v-model="_value"
        :multiple="maxNumber > 1"
        :max-count="maxNumber > 0 ? maxNumber : 99"
        deletable
        :before-delete="handleRemove"
        upload-text="选择图片"
        :after-read="afterRead"
        :max-size="maxSize * 1024 * 1024"
      /> -->
    </template>
  </van-field>
  <view class="file-desc">{{ props.placeholder }} (每张图片不能超过{{ maxSize }}M)</view>
</template>
<script setup lang="ts">
  import { isEmpty } from '@/utils/is';
  import { uploadFiles } from '@/utils/fileUtils';
  import { ref, computed, watch } from 'vue';
  import { evalFormual } from '@/utils/evalFormual';
  import { FieldInputAlign } from '@/enums/formEnum';
  import { Toast } from '@/utils/uniapi/prompt';
  import { BASE_URL } from '@/utils/http/index';
  import { onLoad } from '@dcloudio/uni-app';

  const emits = defineEmits(['update:value', 'labelShow']);

  const props = defineProps({
    value: {
      type: Array,
      default: () => [],
    },
    required: {
      type: Boolean,
      default: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    //隐藏组件的公共属性
    formula: {
      type: Object,
      default: () => {
        return {
          showFormula: '', //回显用，因为包含表单字段的时候会出现表单名称
          calcFormula: '', //解析用，表单名称对应为formData.fieldxxxx
        };
      },
    },
    formItem: {
      type: Object,
      default: () => {},
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    rule: {
      type: Object,
      default: () => null,
    },
    placeholder: {
      type: String,
      default: '请选择图片',
    },
    enableScan: {
      type: Boolean,
      default: false,
    },
    hidden: {
      type: Boolean,
      default: false,
    },
  });

  // 数量限制
  const maxNumber = ref<number>(props.formItem.props.maxNumber);

  // 大小限制
  const maxSize = ref<number>(props.formItem.props.maxSize);

  /** 计算属性：_value */
  const _value = computed({
    get() {
      // return props.value.map((f: any) => {
      //   console.info(JSON.stringify(f));
      //   return {
      //     name: f.name,
      //     url: getRes(f.url),
      //     status: 'success',
      //   };
      // });
      return props.value;
    },
    set(val) {
      emits('update:value', val);
    },
  });

  const getRes = (url: string) => {
    const reg = /^(http:|https:).*/gi;
    return reg.test(url) ? url : BASE_URL + url;
  };

  /** 校验规则 */
  const rules = computed(() => {
    if (isEmpty(props.rule)) {
      return [];
    } else {
      return props.rule;
    }
  });

  const afterRead = (file: any) => {
    if (Array.isArray(file)) {
      file.forEach((fl) => {
        uploadFile(fl);
      });
    } else {
      uploadFile(file);
    }
  };

  /**
   * 上传附件
   * @param file 附件
   */
  const uploadFile = (file: any) => {
    uploadFiles(file, true, (res: any) => {
      if (res.code === 0) {
        _value.value.push(res.data);
        Toast('上传成功');
      }
    });
  };

  /**
   * 移除附件
   * @param file 附件
   * @param fileList 已上传附件数组
   */
  const handleRemove = (file: any, fileList: Array<any>) => {
    let i = _value.value.findIndex((v: any) => v.name === file.name);
    if (i > -1) {
      //this.removeFile(this._value[i].id)
      _value.value.splice(i, 1);
    }
    console.log('删除文件', file);
  };

  const doFormula = () => {
    let hidden = evalFormual(props.formula.calcFormula, props.formData);
    //如果隐藏，同时也隐藏label,通知父组件去隐藏，因为label不在当前界面
    //调用父组件FormDesignRender 的方法：
    emits('labelShow', props.formItem, hidden);
  };

  watch(
    () => props.formData,
    () => {
      doFormula();
    },
    { immediate: true, deep: true },
  );

  onLoad(() => {
    console.info(props.formItem);
  });
</script>
<style scoped lang="scss">
  .file-desc {
    background-color: #ffffff;
    height: 40rpx;
    line-height: 1;
    text-align: left;
    padding-left: 32rpx;
    font-size: 28rpx;
    color: #323233;
  }
</style>
